<template>
  <FModal width="900" :header="header" ref="refFModal" @ok="close">
    <FlowModel ref="refFlowModel"
               @flowElementClick="flowElementClick"/>
  </FModal>
  <TaskHistoryInfo ref="refTaskHistoryInfo"/>
</template>

<script setup>
import FModal from '@/components/FModal/index.vue';
import {defineOptions, ref} from 'vue';
import FlowModel from '@/components/flow/FlowModel.vue';
import {isEmpty} from '@/utils/CommonUtils';
import {getAction} from '@/request/BaseRequest';
import TaskHistoryInfo from '@/components/platwork/FlowModelWithHistory/TaskHistoryInfo.vue';

defineOptions({
  name: 'FlowModelWithHistory'
})
const refFModal = ref(null);
const refFlowModel = ref(null);
const refTaskHistoryInfo = ref(undefined);
const header = ref('查看流程');
const processInstanceId = ref(undefined);

function setProcessHistory(flowImageHistory) {
  flowImageHistory.flowModel = JSON.parse(flowImageHistory.flowDefinition);

  refFlowModel.value.setData(flowImageHistory.flowModel);
  refFlowModel.value.setFlowImageHistory(flowImageHistory);
}

function loadProcessHistoryByProcessInstanceId(processInstanceId) {
  if (isEmpty(processInstanceId)) return;
  getAction('/flow/loadProcessHistoryByProcessInstanceId',
    {processInstanceId}).then(data => {
    if (data.success) {
      let result = data.result;
      setProcessHistory(result);
    }
  });
}

function close() {
  refFModal.value.close();
}

function flowElementClick(element) {
  refTaskHistoryInfo.value.setData(element, processInstanceId.value);
}

function setData(_processInstanceId) {
  processInstanceId.value = _processInstanceId;
  refFModal.value.open();
  loadProcessHistoryByProcessInstanceId(_processInstanceId);
}

function setHeader(headerText) {
  header.value = headerText;
}

defineExpose({
  setData,
  setHeader
});
</script>
